package com.hzaupj.znz;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import com.hzaupj.znz.db.Head;
import com.hzaupj.znz.util.FragmentUtils;
import com.hzaupj.znz.widgets.PicturePicker;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

@ContentView(R.layout.activity_main)
public class MainActivity extends FragmentActivity implements PicturePicker.OnPictureFetchedListener {

    @ViewInject(R.id.webview)
    private WebView webview;

    private String centerSrc = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);

        webview.getSettings().setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }
        webview.getSettings().setAllowFileAccess(true);
        webview.setWebChromeClient(new WebChromeClient());
        webview.addJavascriptInterface(new Object() {
            public void selectPic() {
                takePic();
            }

            public String getPicUrl() {
                return centerSrc;
            }
            public void saveAll(String all) {
                Toast.makeText(MainActivity.this, all, Toast.LENGTH_SHORT).show();
            }
        }, "android");
        webview.loadUrl("file:///android_asset/index.html");
    }

    public void takePic() {
        PicturePicker dialog = PicturePicker.newPictureInstance(MainActivity.this, false);
        FragmentUtils.showSingle(MainActivity.this, dialog, PicturePicker.TAG);
    }

    @Override
    public void onPictureFetched(Uri uri) {
        String url = uri.getPath();
        centerSrc = url;
        webview.loadUrl("file:///android_asset/main.html");
    }

    @Override
    protected void onPause() {
        super.onPause();


//        DbUtils db = DbUtils.create(this, "znz.db");
//        db.configAllowTransaction(true);
//
//        Head head = new Head();
//        head.setHeight(10);
//        head.setWidth(20);
//        head.setSrc("111111111");
//        try {
//            db.save(head);
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
    }
}

